package com.base.cn.platform.os.interceptor;

import com.base.cn.platform.os.common.constants.CommonConstants;
import com.base.cn.platform.os.common.utils.web.DeviceUtils;
import com.base.cn.platform.os.common.utils.web.WebUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 访问路径拦截器,如果使用非手机浏览器访问时自动路径PC站
 *
 * @author s.li
 * @create 2018-10-16-14:46
 */
@Slf4j
public class MobileAccessJumpInterceptor implements HandlerInterceptor {
    @Autowired
    private CommonConstants commonConstants;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        log.info("==========================request rul :"+request.getRequestURL().toString());
        String params = WebUtils.getRequestParameter(request);
        log.info("==========================request params :"+params);
        boolean isMobile = DeviceUtils.isMobileDevice(request);
        log.info("==========================isMobile :"+isMobile);
        //检查是否来自pc端浏览器的请求
        String requestURI = request.getRequestURI();
        if(!isMobile){
            StringBuilder webPath = new StringBuilder(commonConstants.get(CommonConstants.WEB_PATH));
            switch (requestURI){
                case "/mobile/course/info":
                    webPath.append("/web/course/courseInfo?").append(params);
                    break;
                case "/mobile/class/info":
                    webPath.append("/web/classes/info?").append(params.replace("classId","id"));
                    break;
                case "/mobile/class/topic/info":
                    webPath.append("/web/classes/topic/info?").append(params);
                    break;
                case "/mobile/course/liveInfo":
                    webPath.append("/web/course/liveInfo?").append(params);
                    break;
                case "/mobile/article/articleInfoById":
                    webPath.append("/web/article/articleInfoById?").append(params);
                    break;
            }
            response.sendRedirect(webPath.toString());
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
